//import angular core
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';

//import third package
import 'rxjs/add/operator/toPromise';

//import class
import { Hotel } from '../domain/hotel';

@Injectable()
export class HotelService {
  private api_url = 'http://localhost:3000/hotels';
  private headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(private http: Http) { }

  //select all Hotels
  getHotels(): Promise<Hotel[]> {
    const url = `${this.api_url}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Hotel[])
      .catch(this.handleError);
  }

  //select Hotel by id
  getHotelById(id: number): Promise<Hotel> {
    const url = `${this.api_url}/${id}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Hotel)
      .catch(this.handleError);
  }

  //create a Hotel
  createHotel(hotel: Hotel): Promise<Hotel> {
    const url = `${this.api_url}`;
    return this.http
      .post(url, JSON.stringify(hotel), { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Hotel)
      .catch(this.handleError);
  }

  //update a Hotel
  updateHotel(hotel: Hotel): Promise<Hotel> {
    const url = `${this.api_url}/${hotel.id}`;
    return this.http
      .put(url, JSON.stringify(hotel), { headers: this.headers })
      .toPromise()
      .then(() => hotel)
      .catch(this.handleError);
  }

  //delete a Hotel
  deleteHotel(hotel: Hotel): Promise<void> {
    const url = `${this.api_url}/${hotel.id}`;
    return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}
